package com.xtayfjpk.security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.junit.Test;

public class SymmetricAlgorithmTest {
	
	@Test
	public void testCipher() throws Exception {
		KeyGenerator generator = KeyGenerator.getInstance("DES");
		SecretKey secretKey = generator.generateKey();
		System.out.println(secretKey.getEncoded().length);
		
		
		//也可以使用二进制编码
		SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), "DES");
		secretKey = secretKeySpec;
		
		String myInfo = "我的测试信息";
		Cipher cipher = Cipher.getInstance("DES");
		cipher.init(Cipher.ENCRYPT_MODE, secretKey);
		byte[] ciphered = cipher.doFinal(myInfo.getBytes());
		
		cipher.init(Cipher.DECRYPT_MODE, secretKey);
		byte[] deciphered = cipher.doFinal(ciphered);
		String newInfo = new String(deciphered);
		System.out.println(myInfo.equals(newInfo));
	}
}
